#Code working for Webfest!

import cgi
import commandprocessor
import urllib
import datetime
import logging

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class UserInfo(db.Model):
    playerID = db.StringProperty()
    loc_lat = db.StringProperty()
    loc_long = db.StringProperty()
    team = db.StringProperty()
    userClass = db.StringProperty()
    heading = db.StringProperty()
    gpsAccuracy = db.StringProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    playerGameID = db.StringProperty()

class GameSession(db.Model):
    gameName = db.StringProperty()
    teams = db.StringListProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    date2 = db.DateTimeProperty(auto_now=True)
    teamAscore = db.IntegerProperty()
    teamBscore = db.IntegerProperty()
    teamAHasXToPlace = db.IntegerProperty()
    teamBHasXToPlace = db.IntegerProperty()

class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.out.write('<html><body>')
        inGameID=self.request.get('gameID', 'Webfest_Game')
        self.response.out.write("""
              <form action="/update?%s" method="post">
                <div><textarea name="playerID" rows="1" cols="60">myID</textarea></div>
                <div><textarea name="latitude" rows="1" cols="60">34.020924</textarea></div>
                <div><textarea name="longitude" rows="1" cols="60">-118.283135</textarea></div>
                <div><textarea name="team" rows="1" cols="60">Webfest A</textarea></div>
                <div><textarea name="userClass" rows="1" cols="60">Normal Class</textarea></div>
                <div><textarea name="heading" rows="1" cols="60">240</textarea></div>
                <div><textarea name="gpsAccuracy" rows="1" cols="60">20</textarea></div>
                <div><textarea name="command" rows="1" cols="60"></textarea></div>
                <div><input type="submit" value="Update Player in %s"></div>
              </form>
              <form action="/command?%s" method="post">
                <div><textarea name="playerID" rows="1" cols="60">myID</textarea></div>
                <div><textarea name="command" rows="1" cols="60"></textarea></div>
                <div><input type="submit" value="Send Command to %s"></div>
              </form>
              <form action="/create" method="post">
                <div><textarea name="newGameID" rows="1" cols="60">Webfest_Game</textarea></div>
                <div><textarea name="gameName" rows="1" cols="60">A descriptive game name</textarea></div>
                <div><textarea name="teams" rows="1" cols="60">Webfest A</textarea></div>
                <div><textarea name="teams" rows="1" cols="60">Webfest B</textarea></div>
                <div><input type="submit" value="Create Game"></div>
              </form>
            </body>
          </html>""" % (urllib.urlencode({'gameID': inGameID}),
                    cgi.escape(inGameID),
                    urllib.urlencode({'gameID': inGameID}),
                    cgi.escape(inGameID)))
        
class singleCommand(webapp.RequestHandler):
    def post(self):
        logging.info('command sent is: %r, action is singleCommand', self.request.get('command'))
        inGameID=self.request.get('gameID', 'undefined_Game')
        myPlayerID = myPlayerID=self.request.get('playerID', 'no_player_id').rstrip()
        myPlayerID = myPlayerID.replace('\n','')
        myPlayerID = myPlayerID.replace('\r','')
        if self.request.get('command') != '':
            parentKey=db.Key.from_path('GameSession', inGameID)
            databaseKeyName=myPlayerID
            userinfo = UserInfo.get_by_key_name(databaseKeyName, parentKey)
            self.response.out.write(commandprocessor.input(self.request.get('command'), userinfo))
        else:
            self.redirect('/admin?' + urllib.urlencode({'gameID': inGameID}))

class createGame(webapp.RequestHandler):
    def post(self):
        logging.info('command sent is: %r, action is createGame', self.request.get('command'))
        gamesession = GameSession(key_name=self.request.get('newGameID'))
        gamesession.gameName = self.request.get('gameName')
        gamesession.teams = self.request.get_all('teams') 
        gamesession.teamAscore = 0
        gamesession.teamBscore = 0
        gamesession.teamAHasXToPlace = 1
        gamesession.teamBHasXToPlace = 1
        gamesession.put()   
        self.redirect('/admin?' + urllib.urlencode({'gameID': self.request.get('newGameID')}))

class Update(webapp.RequestHandler):
    def post(self):
        logging.info('command sent is: %r, action is Update', self.request.get('command'))
        inGameID=self.request.get('gameID', 'Webfest_Game')
        parentKey=db.Key.from_path('GameSession', inGameID)
        myPlayerID=self.request.get('playerID', 'no_player_id').rstrip()
        if myPlayerID=='':
            myPlayerID="Default User"
        myPlayerID = myPlayerID.replace('\n','')
        myPlayerID = myPlayerID.replace('\r','')
        databaseKeyName=myPlayerID
        userinfo = UserInfo(key_name=databaseKeyName, parent=parentKey)
        logging.info('playerID from post is: %r', self.request.get('playerID', 'no_player_id'))
        logging.info('stripped playerID is: %r', myPlayerID)
        userinfo.playerID = myPlayerID
        userinfo.loc_lat = self.request.get('latitude', 0.0)
        userinfo.loc_long = self.request.get('longitude', 0.0)
        userinfo.team = self.request.get('team', 'Rogue')
        #really, clean up this code
        if len(userinfo.team)<4:
            if len(myPlayerID)&1:
                logging.info('No team found(team was %r, setting team to Webfest A', userinfo.team)
                userinfo.team='Webfest A'
            else:
                logging.info('No team found(team was %r, setting team to Webfest B', userinfo.team)
                userinfo.team='Webfest B'
        userinfo.userClass = self.request.get('userClass', 'NoClass')
        userinfo.heading = self.request.get('heading', 0.0)
        userinfo.gpsAccuracy = self.request.get('gpsAccuracy', 5.0)
        userinfo.playerGameID = inGameID
        if float(userinfo.gpsAccuracy)<11.0:
            userinfo.gpsAccuracy=11.0
        userinfo.put()
        if self.request.get('command') != '':
            myoutput=commandprocessor.input(self.request.get('command'), userinfo)
            logging.info("returned info is: '%r'", myoutput)
            self.response.out.write(myoutput)
        else:
            gamesession = GameSession.get_by_key_name(inGameID)
            if gamesession == None:
                gamesession = GameSession(key_name=inGameID)
                gamesession.gameName = "Auto-Generated Game"
                gamesession.teams = ["Webfest A", "Webfest B"]
                gamesession.teamAscore = 0
                gamesession.teamBscore = 0
                gamesession.teamAHasXToPlace = 1
                gamesession.teamBHasXToPlace = 1
                gamesession.put()   
            Ascore = gamesession.teamAscore
            Bscore = gamesession.teamBscore
            if userinfo.team=='Webfest A':
                IteamstoPlace = gamesession.teamAHasXToPlace
            else:
                IteamstoPlace = gamesession.teamBHasXToPlace
#            dtA = datetime.datetime.now() - gamesession.date
#            minsA = dtA.seconds / 60 
            dtB = datetime.datetime.now() - gamesession.date2
            minsB = dtB.seconds / 60
#            if minsA>4:
#                commandprocessor.settingTreasure(userinfo)
            if minsB>3:
                commandprocessor.settingTreasure(userinfo)
            mysecondout = str(Ascore) + " " + str(Bscore) + " " + str(IteamstoPlace)
            logging.info("returned info on just update is: '%r'", mysecondout)
            self.response.out.write(mysecondout)
#            self.redirect('/admin?' + urllib.urlencode({'gameID': inGameID}))


application = webapp.WSGIApplication(
                                     [('/admin', MainPage),
                                      ('/update', Update),
                                      ('/command', singleCommand),
                                      ('/create', createGame)
                                      ],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()